package com.xms.security.api.controller;

import com.xms.core.annotation.AllowAnonymous;
import com.xms.core.org.UserContext;
import com.xms.organization.entity.Organization;
import com.xms.organization.entity.Systemuser;
import com.xms.organization.service.IBusinessUnitService;
import com.xms.organization.service.IOrganizationService;
import com.xms.security.entity.RoleMemberShip;
import com.xms.security.identity.IAuthenticationService;
import com.xms.security.service.IAccountService;
import com.xms.security.service.principal.ISystemUserRolesService;
import com.xms.security.verification.core.IVerifyProvider;
import com.xms.utils.CollectionUtil;
import com.xms.utils.StringUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * AccountController
 * </p>
 *
 * @author migo
 * @since 2021/8/31
 */
@RestController
@RequestMapping({"/api/account", "/{org}/api/account"})
public class AccountController extends ApiBaseController {
    private IAuthenticationService _authenticationService;
    private IAccountService _accountService;
    private ISystemUserRolesService _systemUserRolesService;
    private IOrganizationService _organizationService;
    private IBusinessUnitService _businessUnitService;
    private IVerifyProvider _verifyProvider;

    @Autowired
    public void AccountController(IAuthenticationService authenticationService,
                                  IAccountService accountService,
                                  ISystemUserRolesService systemUserRolesService,
                                  IOrganizationService organizationService,
                                  IBusinessUnitService businessUnitService,
                                  IVerifyProvider verifyProvider) {
        _authenticationService = authenticationService;
        _accountService = accountService;
        _systemUserRolesService = systemUserRolesService;
        _organizationService = organizationService;
        _businessUnitService = businessUnitService;
        _verifyProvider = verifyProvider;
    }

    /**
     * 用户登录认证
     */
    @AllowAnonymous
    @PostMapping(value = "signin")
    public JsonResultObject signIn(@RequestParam(value = "orguniquename", required = true) String orgUniqueName,
                                   @RequestParam(value = "loginname", required = true) String loginName,
                                   @RequestParam(value = "password", required = true) String password,
                                   @RequestParam(value = "verifycode", required = true) String verifyCode) {
        if (StringUtil.isEmpty(loginName) || StringUtil.isEmpty(password)) {
            return JError("请输入帐号和密码");
        }
        if(!_verifyProvider.valid(verifyCode)){
            return JError("验证码错误");
        }
        Organization orgInfo = _organizationService.getByUniqueName(orgUniqueName);
        if(orgInfo == null){
            return JError("组织不存在");
        }
        JsonResultObject result = new JsonResultObject(false);
        StringBuffer msg = new StringBuffer();
        try {
            //查询用户
            Systemuser systemUser = _accountService.getByAccountName(loginName);
            if (systemUser == null) {
                msg.append("帐号不存在");
            } else if (!systemUser.getStatecode()) {
                msg.append("帐号已禁用");
            } else if (_accountService.isValidePassword(password, systemUser.getPassword())) {
                //登录状态记录
                UserContext ctx = new UserContext();
                ctx.BusinessUnitId = systemUser.getBusinessunitid();
                ctx.BusinessUnitIdName = _businessUnitService.getById(systemUser.getBusinessunitid()).getName();
                ctx.AccountName = systemUser.getAccountname();
                ctx.OrganizationId = systemUser.getOrganizationid();
                ctx.UserName = systemUser.getName();
                ctx.SystemUserId = systemUser.getSystemuserid();
                ctx.IsSuperAdmin = _systemUserRolesService.isAdministrator(systemUser.getSystemuserid());
                ctx.OrganizationUniqueName = orgInfo.getUniquename();
                List<RoleMemberShip> roles = _systemUserRolesService.getByUserId(ctx.SystemUserId);
                if (CollectionUtil.notEmpty(roles)) {
                    ctx.roles = roles.stream().map(x -> x.getRoleid()).collect(Collectors.toList());
                }
                _authenticationService.signIn(_request, ctx, true);
                //更新最后登录时间
                _accountService.updateLastLoginTime(systemUser.getSystemuserid());
                result = JOk(systemUser);
            } else {
                msg.append("密码有误");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            result = JError("发生异常");
        }
        if (msg.length() > 0) {
            return JError(msg.toString());
        }
        return result;
    }

    @AllowAnonymous
    @RequestMapping(value = "/signout", method = RequestMethod.GET)
    public JsonResultObject signOut() throws ServletException {
        _authenticationService.signOut(_request);
        return JOk();
    }
}
